import {
  addPlatFormRole,
  deletePlatFormRole,
  editPlatFormRole,
  selectAllPlatFormRole
} from '@/api/conf'
import { CoustomTableFn } from '@/components/table'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import { FormInstance } from 'ant-design-vue'
import { PropType } from 'vue'
import './components.less'

/** 状态数据 */
interface Conf_administrator_state {
  /**弹窗 */
  modal: {
    /**弹窗 关闭*/
    visible: boolean
    /**弹窗 类型*/
    type: string
    /**弹窗 标题*/
    title: string
    /**  弹窗 修改 数据源 */
    edit_source: {
      dictCode: string
      dictName: string
      dictDesc: string
      dictValue: string
      sort: string
    }
    /**  弹窗 修改 数据源 */
    add_source: {
      dictDesc: string
      dictName: string
    }
  }
  table: {
    dataSource: SysDict.Item[]
    loading: boolean
  }
}
let conf_administrator_state = reactive<Conf_administrator_state>({
  modal: {
    visible: false,
    type: '',
    title: '',
    edit_source: {
      dictCode: '',
      dictName: '',
      dictDesc: '',
      dictValue: '',
      sort: ''
    },
    add_source: {
      dictDesc: '',
      dictName: ''
    }
  },
  table: {
    dataSource: [],
    loading: false
  }
})

/**获取表格数据 */
export async function getTableDatas(data?: any) {
  let { dataSource, loading } = toRefs(conf_administrator_state.table)
  loading.value = true
  let res = await selectAllPlatFormRole().catch(err => {})
  if (res) {
    dataSource.value = res.data
  }
  loading.value = false
}

/** 主体窗口 头部 操作栏 */
export const MainViewNav = defineComponent({
  setup() {
    let { visible, title, type } = toRefs(conf_administrator_state.modal)
    const handle_add_btn_click = () => {
      visible.value = true
      type.value = 'addRole'
      title.value = '添加角色'
    }
    return () => (
      <div class='h-mainViewNav border-b border-default bg-white px-4 flex justify-start items-center'>
        <a-button type='primary' onClick={handle_add_btn_click}>
          添加角色
        </a-button>
      </div>
    )
  }
})

/** 表格 操作栏 */
export const TypeHandleBtn = defineComponent({
  props: {
    record: {
      type: Object as PropType<SysDict.Item>,
      default: {}
    }
  },
  setup(props) {
    let { router } = useGlobalAPI()
    let { visible, title, type, edit_source } = toRefs(conf_administrator_state.modal)
    const handle_type_edit_btn_click = () => {
      visible.value = true
      type.value = 'editRole'
      title.value = '修改'
      Object.keys(edit_source.value).forEach(key => {
        // @ts-ignore
        edit_source.value[key as keyof typeof edit_source.value] = props.record[key]
      })
    }
    const handle_checkAuth_click = () => {
      router.push({
        path: '/conf/role/api',
        query: {
          roleCode: props.record.dictCode,
          roleName: props.record.dictName
        }
      })
    }
    const handle_checkModules_click = () => {
      router.push({
        path: '/conf/role/modules',
        query: {
          roleCode: props.record.dictCode,
          roleName: props.record.dictName
        }
      })
    }
    const handle_delete_click = async () => {
      await deletePlatFormRole({ dictCode: props.record.dictCode }).catch(err => {})
      getTableDatas()
    }
    return () => (
      <div class='text-right'>
        <span class='mr-2 text-primary border-b cursor-pointer' onClick={handle_checkAuth_click}>
          查看权限
        </span>
        <span class='mr-2 text-primary border-b cursor-pointer' onClick={handle_checkModules_click}>
          查看界面配置
        </span>
        <span
          class='mr-2 text-primary border-b cursor-pointer'
          onClick={handle_type_edit_btn_click}
        >
          编辑
        </span>
        <a-popconfirm
          title={`确认删除 ${props.record.dictName} 角色吗?`}
          placement='topRight'
          ok-text='确认'
          cancel-text='取消'
          onConfirm={handle_delete_click}
          onCancel={() => {}}
        >
          <span class='mr-2 text-primary border-b cursor-pointer'>删除</span>
        </a-popconfirm>
      </div>
    )
  }
})

/** 表格 */
const CoustomTable = CoustomTableFn<SysDict.Item>()
export const MainViewContentTable = defineComponent({
  name: 'MainViewContent',
  setup(props) {
    let { dataSource, loading } = toRefs(conf_administrator_state.table)

    let columns: CColumn<any>[] = [
      {
        title: '角色',
        dataIndex: 'dictName',
        ellipsis: true
      },
      {
        title: '备注',
        dataIndex: 'dictDesc',
        ellipsis: true
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        ellipsis: true
      },
      {
        title: '操作',
        dataIndex: 'utils',
        isUtil: true
      }
    ]

    return () => (
      <CoustomTable
        dataSource={dataSource.value}
        loading={loading.value}
        rowKey='dictTypeCode'
        columns={columns}
        showPagination={false}
      >
        {{
          util: (record: SysDict.Item) => <TypeHandleBtn record={record}></TypeHandleBtn>
        }}
      </CoustomTable>
    )
  }
})

/**弹窗 表单 添加用 */
const AddFormOfModal = defineComponent({
  name: 'AddFormOfModal_role',
  emits: ['finish'],
  setup(props, { emit }) {
    let formRef = ref<FormInstance>()
    let { add_source } = toRefs(conf_administrator_state.modal)
    let onLoading = ref(false)
    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      onLoading.value = true
      await addPlatFormRole(add_source.value).catch(err => {})
      setTimeout(() => {
        returnEmit()
      }, 300)
    }
    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      console.log('handle_form_finish_failed', add_source.value)
      returnEmit()
    }
    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      returnEmit()
    }
    // 清空表单 关闭外层弹框
    const returnEmit = () => {
      onLoading.value = false
      formRef.value?.resetFields()
      emit('finish')
    }

    return () => (
      <a-form
        v-model={[formRef, 'ref']}
        name='addSysdictType'
        model={add_source.value}
        label-col={{ span: 4 }}
        wrapper-col={{ span: 16 }}
        onFinish={handle_form_finish}
        onFinishFailed={handle_form_finish_failed}
      >
        <a-form-item label='角色' name='dictName'>
          <a-input v-model={[add_source.value.dictName, 'value']} />
        </a-form-item>
        <a-form-item label='备注' name='dictDesc'>
          <a-input v-model={[add_source.value.dictDesc, 'value']} />
        </a-form-item>

        <a-form-item>
          <a-button
            type='primary'
            class='float-right mx-4'
            html-type='submit'
            loading={onLoading.value}
          >
            提交
          </a-button>
          <a-button class='float-right mx-4' onClick={handle_form_cancel}>
            取消
          </a-button>
        </a-form-item>
      </a-form>
    )
  }
})

/**弹窗 表单 修改用 */
const EditFormOfModal = defineComponent({
  name: 'EditFormOfModal_role',
  emits: ['finish'],
  setup(props, { emit }) {
    let { edit_source } = toRefs(conf_administrator_state.modal)
    let formRef = ref<FormInstance>()

    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      await editPlatFormRole(edit_source.value).catch(err => {})
      setTimeout(() => {
        returnEmit()
      }, 300)
    }
    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      console.log('handle_form_finish_failed', edit_source.value)
      returnEmit()
    }
    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      returnEmit()
    }
    // 清空表单 关闭外层弹框
    const returnEmit = () => {
      formRef.value?.resetFields()
      emit('finish')
    }
    return () => (
      <a-form
        v-model={[formRef, 'ref']}
        name='editSysdictType'
        model={edit_source.value}
        label-col={{ span: 4 }}
        wrapper-col={{ span: 16 }}
        onFinish={handle_form_finish}
        onFinishFailed={handle_form_finish_failed}
      >
        <a-form-item label='角色' name='dictName'>
          <a-input v-model={[edit_source.value.dictName, 'value']} />
        </a-form-item>
        <a-form-item label='备注' name='dictDesc'>
          <a-input v-model={[edit_source.value.dictDesc, 'value']} />
        </a-form-item>
        <a-form-item>
          <a-button type='primary' class='float-right mx-4' html-type='submit'>
            提交
          </a-button>
          <a-button class='float-right mx-4' onClick={handle_form_cancel}>
            取消
          </a-button>
        </a-form-item>
      </a-form>
    )
  }
})

/** 弹窗 */
export const MainViewModel = defineComponent({
  setup(props, { emit }) {
    let { visible, type, title } = toRefs(conf_administrator_state.modal)
    const handle_form_finish = () => {
      visible.value = false
      type.value = ''
      title.value = ''
      getTableDatas()
    }
    return () => {
      let dynamicCom
      switch (type.value) {
        case 'addRole':
          dynamicCom = <AddFormOfModal onFinish={handle_form_finish}></AddFormOfModal>
          break
        case 'editRole':
          dynamicCom = <EditFormOfModal onFinish={handle_form_finish}></EditFormOfModal>
          break
      }
      return (
        <a-modal
          visible={visible.value}
          title={title.value}
          footer={null}
          onCancel={() => {
            handle_form_finish()
          }}
        >
          {dynamicCom}
        </a-modal>
      )
    }
  }
})
